package com.ssoserver.config;

import com.google.common.collect.Maps;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Bean(name = "master")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "slave0")
    @ConfigurationProperties(prefix = "spring.datasource.slave0")
    public DataSource slave0DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "slave1")
    @ConfigurationProperties(prefix = "spring.datasource.slave1")
    public DataSource slave1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DataSource myRoutingDataSource() {
        DynamicDatabase dynamicDataSource = new DynamicDatabase();
        //设置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource());
        Map<Object, Object> targetDataSources = Maps.newHashMap();
        targetDataSources.put("master", masterDataSource());
        targetDataSources.put("slave0", slave0DataSource());
        targetDataSources.put("slave1", slave1DataSource());
        dynamicDataSource.setTargetDataSources(targetDataSources);
        return dynamicDataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(myRoutingDataSource());
    }
}
